<script setup lang="ts">
import {onLoad, onReachBottom} from '@dcloudio/uni-app'
import { switchNavBarTheme } from '@/utils/common'
import { reactive, ref } from 'vue'
import Coupon from '@/components/Coupon.vue'
import type { CouponRecordVO, QueryParams } from '@/types/reward'
import { getInvalidCouponByPageAPI, getUnusedCouponAPI } from '@/api/reward'
import type { LoadMoreState } from 'wot-design-uni/components/wd-loadmore/types'

const unusedCoupons = reactive<CouponRecordVO[]>([])
onLoad(async () => {
  switchNavBarTheme()
  const res = await getUnusedCouponAPI()
  if (res.code === 200) Object.assign(unusedCoupons, res.data)
})

const current = ref<0 | 1>(0)
const list = ref<{ value: number; payload: string }[]>([
  { value: 0, payload: '未使用' },
  { value: 1, payload: '已失效' },
])

const queryParams = reactive<QueryParams>({
  page: 1,
  pageSize: 6,
})
const listInfo = reactive<{ state: LoadMoreState, isLoaded: boolean }>({ state: 'loading', isLoaded: false })
const invalidCoupons = reactive<CouponRecordVO[]>([])
const changeList = async () => {
  if (current.value === 1 && !listInfo.isLoaded) {
    const res = await getInvalidCouponByPageAPI(queryParams)
    if (res.code === 200) Object.assign(invalidCoupons, res.data)
    listInfo.isLoaded = true
    if (invalidCoupons.length < queryParams.pageSize) listInfo.state = 'finished'
  }
}

const loadmore = async () => {
  if (listInfo.state !== 'finished') {
    queryParams.page++
    const res = await getInvalidCouponByPageAPI(queryParams)
    if (res.code === 200) {
      invalidCoupons.push(...res.data)
      if (res.data.length < queryParams.pageSize) listInfo.state = 'finished'
    }
    else {
      listInfo.state = 'error'
      queryParams.page--
    }
  }
}

onReachBottom(() => {
  if (current.value === 1 && listInfo.state === 'loading') loadmore()
})
</script>

<template>
  <wd-segmented @change="changeList" :options="list" v-model:value="current">
    <template #label="{ option }">
      <view>{{ option.payload }}</view>
    </template>
  </wd-segmented>
  <view v-if="current === 0">
    <view v-if="unusedCoupons.length > 0" style="padding: 20rpx">
      <Coupon v-for="item in unusedCoupons" :data="item" />
    </view>
    <wd-status-tip
      v-else
      custom-class="custom-class"
      image-size="700rpx"
      image="content"
      tip="暂无记录"
    />
  </view>
  <view v-else>
    <view v-if="invalidCoupons.length > 0" style="padding: 20rpx">
      <Coupon v-for="item in invalidCoupons" :data="item" />
      <wd-loadmore @reload="loadmore" :state="listInfo.state" finished-text="没有更多了" />
    </view>
    <wd-status-tip
      v-else
      custom-class="custom-class"
      image-size="700rpx"
      image="content"
      tip="暂无记录"
    />
  </view>
</template>

<style scoped lang="scss">
:deep(.custom-class) {
  .wd-status-tip__text {
    font-size: 42rpx;
  }
}
</style>
